package com.br.aiops.config;

import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@Data
public class ElasticSearchSpringConfig {

    @Value("${spring.es.scheme}")
    private String scheme;

    @Value("${spring.es.hostname}")
    private String hostname;

    @Value("${spring.es.port}")
    private int port;

    @Value("${spring.es.username}")
    private String username;

    @Value("${spring.es.password}")
    private String password;

    @Value("${spring.es.timeout}")
    private int timeout;

    @Bean
    public RestClient restClient() {
        return RestClient.builder(getHttpHosts())
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    httpClientBuilder.disableAuthCaching();
                    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);})
                .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(timeout))
                .build();
    }

    public HttpHost[] getHttpHosts() {
        if (hostname.contains(",")) {
            List<HttpHost> httpHosts = Arrays.stream(hostname.split(",")).map(host -> new HttpHost(host, port, scheme)).collect(Collectors.toList());
            return httpHosts.toArray(new HttpHost[httpHosts.size()]);
        }

        HttpHost[] httpHosts = new HttpHost[1];
        httpHosts[0] = new HttpHost(hostname, port, scheme);
        return httpHosts;
    }
}
